package com.bsbc.project.controller;

import com.bsbc.project.entity.Unit;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 模拟guava 缓存
 */
@RestController
@RequestMapping("/member/guavaCache")
public class GuavaCacheController {


    /**
     * 创建guava缓存   expireAfterWrite:写入缓存后多久过期
     * todo:还可以设置初始缓存容量
     * todo:缓存的清楚策略
     */
    private static Cache<String,String> unitCache = CacheBuilder.newBuilder().expireAfterWrite(3, TimeUnit.MINUTES).build();


    @PostMapping("/getUnitFromCache")
    public String getUnitFromCache(){
        String unitName = unitCache.getIfPresent("0015");
        if (unitName == null) {
            //unitName为空则说明缓存中没有数据
            this.setGuavaCache();
            unitName = unitCache.getIfPresent("0015");
        }
        return unitName;
    }

    /**
     * 当缓存没有数据时，需要调用远程服务获取单位信息
     */
    @PostMapping("/setGuavaCache")
    public void setGuavaCache() {
        //模拟远程获取数据
        List<Unit> units = MysqlController.getUnits();
        for (Unit unit : units) {
            unitCache.put(unit.getUnitCode(),unit.getUnitName());
        }
    }
}
